package JMH.day01;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;

/**
 * 校验JVM循环优化（循环展开）
 */
@Fork(1)
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5)
@Measurement(iterations = 5)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Thread)
public class JMHExample05 {

    private int x = 1;
    private int y = 2;

    private int loopMessage(int times) {
        int sum = 0;
        for (int i = 0; i < times; i++) {
            sum += (x + y);
        }
        return sum;
    }

    @Benchmark
    public int message() {
        return (x + y);
    }

    @Benchmark
    @OperationsPerInvocation
    public int loop_1() {
        return loopMessage(1);
    }
    @Benchmark
    @OperationsPerInvocation(10)
    public int loop_10() {
        return loopMessage(10);
    }
    @Benchmark
    @OperationsPerInvocation(100)
    public int loop_100() {
        return loopMessage(100);
    }
    @Benchmark
    @OperationsPerInvocation(1000)
    public int loop_1000() {
        return loopMessage(1000);
    }

    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(JMHExample05.class.getSimpleName())
                .build();
        new Runner(options).run();
    }
}
